<?php
namespace app\admin\controller;

use app\common\model\CommonModel;
use app\common\model\OrgAttrModel;
use app\common\model\SchoolAttrModel;
use app\common\model\TableCustomFieldModel;
use app\common\model\UserAttrModel;

class Customize extends Common
{
    /**
     * 字段列表
     * @author 贺强
     * @time   2023/6/26 14:06
     * @return array|\think\response\View
     */
    public function lists()
    {
        $where = [];
        $param = $this->request->param();
        if (!empty($param['table_name'])) {
            $where = ['table_name' => $param['table_name']];
        } else {
            $param['table_name'] = '';
        }
        // 分页参数
        $page = $param['page'] ?? 1;
        $pagesize = $param['pagesize'] ?? env('app.pagesize', 20);
        // 排序参数
        $order = ['table_name' => 'asc', 'sort' => 'asc'];
        $list = TableCustomFieldModel::getList($where, true, [$page, $pagesize], $order);
        foreach ($list as &$item) {
            format_datetime($item['ctime']);
            format_datetime($item['mtime']);
        }
        if ($this->request->isAjax()) {
            return ajax('获取成功', 200, $list);
        }
        $count = TableCustomFieldModel::getCount($where);
        $pages = ceil($count / $pagesize);
        $tables = $this->GetCustomFieldTables();
        return view('list', compact('list', 'count', 'pages', 'param', 'tables'));
    }

    /**
     * 添加字段
     * @author 贺强
     * @time   2023/6/26 16:40
     * @return string|\think\response\Json|\think\response\View
     */
    public function add()
    {
        if ($this->request->isPost()) {
            if (!empty($this->admin['code'])) {
                return $this->admin;
            }
            $param = $this->request->post();
            if (empty($param['table_name']) || empty($param['field_txt']) || empty($param['field_type'])) {
                return ajax('参数缺失', 101);
            }
            if ($param['field_type'] === 'radio' || $param['field_type'] === 'select' && (empty($param['fk']) || empty($param['fv']))) {
                return ajax('radio单选或下拉框必须有可选值', 102);
            }
            $field_name = '';
            for ($i = 0; $i < mb_strlen($param['field_txt']); $i++) {
                $s = mb_substr($param['field_txt'], $i, 1);
                $field_name .= get_pinyin($s);
            }
            $data = [
                'table_name' => $param['table_name'],
                'field_txt' => $param['field_txt'],
                'field_type' => $param['field_type'],
                'field_name' => $field_name,
                'sort' => $param['sort'],
                'mtime' => 0,
            ];
            if (!empty($param['fk']) && !empty($param['fv']) && is_array($param['fk']) && is_array($param['fv']) && count($param['fk']) === count($param['fv'])) {
                $field_value = [];
                foreach ($param['fk'] as $k => $v) {
                    if (!empty($v)) {
                        $field_value[] = ['key' => $v, 'value' => $param['fv'][$k]];
                    }
                }
                $data['field_value'] = json_encode($field_value);
            }
            $res = TableCustomFieldModel::add($data);
            if (!$res) {
                return ajax('添加失败', 400);
            }
            return ajax('添加成功');
        }
        $tables = $this->GetCustomFieldTables();
        // 字段类型
        $types = get_field_type();
        return view('', compact('tables', 'types'));
    }

    /**
     * 删除字段
     * @author 贺强
     * @time   2023/6/26 16:42
     * @return string|\think\response\Json|null
     */
    public function del()
    {
        if (!empty($this->admin['code'])) {
            return $this->admin;
        }
        $id = $this->request->post('id', '');
        if (empty($id)) {
            return ajax('非法参数', 301);
        }
        $field = TableCustomFieldModel::getModel(['id' => $id]);
        $res = TableCustomFieldModel::delById($id);
        if (!$res) {
            return ajax('删除失败', 400);
        }
        $prefix = env('database.prefix', '');
        switch ($field['table_name']) {
            case "{$prefix}user":
                $model = new UserAttrModel();
                break;
            case "{$prefix}school":
                $model = new SchoolAttrModel();
                break;
            case "{$prefix}org":
                $model = new OrgAttrModel();
                break;
        }
        $model::delByWhere(['attr_name' => $field['field_name']]);
        return ajax('删除成功');
    }

    /**
     * 修改字段
     * @author 贺强
     * @time   2023/6/25 20:56
     * @return string|\think\response\Json|\think\response\View
     */
    public function edit()
    {
        $id = $this->request->param('id', '');
        $field = TableCustomFieldModel::getModel(['id' => $id]);
        if ($this->request->isPost()) {
            if (!empty($this->admin['code'])) {
                return $this->admin;
            }
            $param = $this->request->param();
            if (empty($param['table_name']) || empty($param['field_txt']) || empty($param['field_type'])) {
                return ajax('参数缺失', 101);
            }
            $data = [
                'table_name' => $param['table_name'],
                'field_txt' => $param['field_txt'],
                'field_type' => $param['field_type'],
                'sort' => $param['sort'],
            ];
            if ($field['field_txt'] !== $param['field_txt'] && !empty($param['is_force'])) {
                $field_name = '';
                for ($i = 0; $i < mb_strlen($param['field_txt']); $i++) {
                    $s = mb_substr($param['field_txt'], $i, 1);
                    $field_name .= get_pinyin($s);
                }
                $data['field_name'] = $field_name;
            }
            if (!empty($param['fk']) && !empty($param['fv']) && is_array($param['fk']) && is_array($param['fv']) && count($param['fk']) === count($param['fv'])) {
                $field_value = [];
                foreach ($param['fk'] as $k => $v) {
                    if (!empty($v)) {
                        $field_value[] = ['key' => $v, 'value' => $param['fv'][$k]];
                    }
                }
                $data['field_value'] = json_encode($field_value);
            }
            $res = TableCustomFieldModel::modify($data, ['id' => $id]);
            if (!$res) {
                return ajax('修改失败', 400);
            }
            return ajax('修改成功');
        }
        if (!empty($field['field_value']) && is_json($field['field_value'])) {
            $field['field_value'] = json_decode($field['field_value'], true);
        }
        $tables = $this->GetCustomFieldTables();
        // 字段类型
        $types = get_field_type();
        return view('', compact('field', 'tables', 'types'));
    }
}
